import store from "@/store";
import {WSMsgContext} from "@/util/wsMsg/msgStrategy";
let url =  (process.env.VUE_APP_BASE_URL.replace('https','ws').replace('http','ws'));
const WS = {
  $ws: null,
  wsUrl: url +'/admin-service/ws/info?access_token=',
  createWS (access_token) {
    if ('WebSocket' in window) {
      this.$ws = new WebSocket(this.wsUrl+access_token)
      this.$ws.onopen = this.wsOpen
      this.$ws.onmessage = this.wsMessage
      this.$ws.onerror = this.wsError
      this.$ws.onclose = this.wsClose
    } else {
      console.log('当前浏览器不支持webSocket')
    }
  },
  wsOpen() {
    heartBeat.start()
  },
  wsMessage:function(msg) {
    heartBeat.reset();
    let m = JSON.parse(msg.data);
    new WSMsgContext().handleMsg(m);
  },
  wsError(err){
  },
  wsClose(event){
  }
}
const heartBeat = {
  timeout: 30000, // 心跳重连时间
  timeoutObj: null, // 定时器
  reset () {
    clearInterval(this.timeoutObj);
    console.log("clearInterval to start")
    this.start()
  },
  start () {
    this.timeoutObj = setInterval(function () {
      if (WS.$ws.readyState === 1) {
        try {
          WS.$ws.send('HeartBeat')
        } catch (err) {
          console.log('断线了: ' + err)
          WS.createWS(store.getters.access_token);
        }
      }
    }, this.timeout)
  }
}
export default WS;
